import { defineComponent, h, ref } from "vue";

// 过滤器 @filter="node => node._selected = true"
const onFilter = "filter";

/**
 * 渲染 dom
 * @param   {Object}  ctx         上下文 vue对象
 * @param   {Object}  parentNode  父节点
 * @param   {Array}   nodes       节点集合
 * @param   {Number}  depth       深度
 * @returns {Array}   VNode
 */
function renderNodes(ctx, parentNode, nodes, depth) {
  nodes = nodes || [];
  return nodes.map(node => {
    // 节点层级
    node._depth = depth;
    // 父节点
    node._parent = parentNode;
    // 节点路径
    const parentPath = (parentNode && parentNode._path) || [];
    node._path = [].concat(parentPath, node);
    // 节点选中状态
    node._selected = false;
    // 节点隐藏状态
    node._hide = false;
    // 过滤器
    ctx.$emit(onFilter, node);

    // 节点关闭状态
    if (node._closed == undefined) {
      node._closed = !node._selected;
      // 如果节点展开，展开祖先节点
      if (!node._closed) {
        parentPath.forEach(parent => {
          parent._closed = false;
        });
      }
    }

    if (node._hide) {
      return undefined;
    }

    // 节点标签原始标题
    const menuTitle = h(
      "div",
      {
        class: 'v-cell__title'
      },
      (ctx.$slots.title && ctx.$slots.title({ node })) || node[ctx.default.name]
    );
    // 节点标签原始icon
    const menuIcon = (ctx.$slots.icon && ctx.$slots.icon({ node })) || h(
      "i",
      {
        class: `x_y_center van-icon van-icon-arrow-${node._closed ? 'down' : 'up'}`
      },
    );
    // 节点标签原始内容
    const menuHtml = h(
      "div",
      {
        class: 'v-cell',
        onclick: () => ctx.onClick(node), // 点击
        
      },
      [
        menuTitle,
        node[ctx.default.children] && node[ctx.default.children].length > 0 ? menuIcon : '',// 有子节点才渲染Icon
      ],
    );
    // 递归
    const subNodes = renderNodes(ctx, node, node[ctx.default.children], depth + 1);
    // 子节点dom
    const subMenu = h(
      "div",
      {
        style: {
          display: node._closed ? "none" : "block",
        },
      },
      subNodes
    );
    // 节点dom
    return h("div", {
      class: 'v-tree pl-15'
    }, [
      menuHtml,
      node[ctx.default.children] && node[ctx.default.children].length > 0 ? subMenu : '',// 有子节点就渲染子节点
    ]);
  });
}

/**
 * 模块定义
 */
export default defineComponent({
  props: {
    data: {
      type: Array,
      required: true,
    },
    default: {
      type: Object,
      default: () => {
        return {
          id: "id",
          name: "title",
          children: "children",
        };
      },
    },
  },

  emits: [onFilter,'click'],

  setup(props, context) {
    const selected = ref([]);
    const onClick = (node) => {
      if (node.children && node.children.length) {
        node._closed = !node._closed;
      }
      context.emit('click', node)
    };
    return {
      selected,
      onClick
    };
  },

  render() {
    return h("div", {
      class: 'tree'
    }, renderNodes(this, null, this.data, 0));
  }
});